package org.codingq92.basic.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: CodingQ92
 * @date: 2025/6/4 23:08
 */
public class ReentrantLockTest {

    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        // tryLock写法
        for (int i = 0; i < 10; i++) {
            new Thread(ReentrantLockTest::trySay, "Thread" + i).start();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }

        // 普通写法ReentrantLock
        for (int i = 0; i < 10; i++) {
            new Thread(ReentrantLockTest::say, "Thread" + i).start();
        }
    }

    private static void trySay() {
        try {
//        if (lock.tryLock()) { // 尝试获取锁 没有获取到就直接结束了
            if (lock.tryLock(2, TimeUnit.SECONDS)) { // 按照指定时间获取锁 没有获取到就直接结束了
                System.out.println(Thread.currentThread().getName() + ">>> try lock say~~~~");
                Thread.sleep(3000);
            } else {
                System.out.println(Thread.currentThread().getName() + ">>> try lock 没有获取到锁,跳过～～～");
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    private static void say() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + ">>> normal lock say~~~~");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
